﻿using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
using System.Web.Routing;
using DHQGHN.Common;
using DHQGHN.DAL.BO.Admin;
using DHQGHN.MVC.Security;
using DHQGHN.PM0.Common.Attributes;
using DHQGHN.PM0.Models.Admin;
using WebMatrix.WebData;

namespace DHQGHN.PM0.Controllers
{
    public class BaseController : Controller
    {
        protected const int PageSize = 10;
        public string adminServiceUrl;
        private GlobalInfo globalInfo;

        public BaseController()
        {
            adminServiceUrl = ConfigurationManager.AppSettings["ADMIN_SERVICE"].ToString();
            ViewBag.Menu = GlobalInfo.User != null ? GlobalInfo.User.ListMenu : null;
        }

        //phunx1, 20150609: lay thong tin chung cua User
        protected virtual MyPrincipal MyUser
        {
            get { return HttpContext.User as MyPrincipal; }
        }

        //Thuoc tinh chua cac thong tin chung cua ung dung
        public GlobalInfo GlobalInfo
        {
            get
            {
                if (globalInfo == null)
                    globalInfo = new GlobalInfo();
                return globalInfo;
            }
        }

        public ActionResult ReturnValue(string msg, bool success = true, object result = null, string actionRedirect = "Index")
        {
            if (Request.IsAjaxRequest())
            {
                if (success)
                    return Json(JsonResponse.Json200(msg, result), JsonRequestBehavior.AllowGet);
                else
                    return Json(JsonResponse.Json500(msg), JsonRequestBehavior.AllowGet);
            }
            else
                return RedirectToAction(actionRedirect);
        }

        public ActionResult ModelErrors(ModelStateDictionary modelState)
        {
            String msg = string.Join("; ", ModelState.Select(u => u.Value).SelectMany(u => u.Errors).Select(u => u.ErrorMessage));
            return ReturnValue(msg, false, null);
            //return Json(new JsonMessage() { Message = string.Join("; ", ModelState.Select(u => u.Value).SelectMany(u => u.Errors).Select(u => u.ErrorMessage)), Type = JsonMessage.Error });
        }

        /// <summary>
        /// Kiem tra truong hop da logoff hoac chua dang nhap thi tro lai trang dang nhap
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var actionName = this.ControllerContext.RouteData.Values["action"].ToString();
            var controllerName = this.ControllerContext.RouteData.Values["controller"].ToString();
            if (GlobalInfo.User == null && !"Login".Equals(controllerName) && Session["AuthToken"] != null && Request.Cookies["AuthToken"] != null)
            {
                if (!Session["AuthToken"].ToString().Equals(Request.Cookies["AuthToken"].Value))
                {
                    filterContext.Result = new RedirectResult("/Login/Index");
                }
                else if (Session["ActionNameInfo"] != null)
                {
                    //if (!Request.IsAjaxRequest())
                    //{
                    //    string url = GetUrl(filterContext.ActionDescriptor);
                    //    if (!IsPermiss(url))
                    //    {
                    //        RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
                    //        redirectTargetDictionary.Add("action", "NotAuthorized");
                    //        redirectTargetDictionary.Add("controller", "Login");
                    //        filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
                    //    }
                    //}
                }
            }
            else if (Session["ActionNameInfo"] != null)
            {
                //if (!Request.IsAjaxRequest())
                //{
                //    string url = GetUrl(filterContext.ActionDescriptor);
                //    if (!IsPermiss(url))
                //    {
                //        RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
                //        redirectTargetDictionary.Add("action", "NotAuthorized");
                //        redirectTargetDictionary.Add("controller", "Login");
                //        filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
                //    }
                //}
            }
            //Quyvd
            if (GlobalInfo.User == null && controllerName != "Login")
                filterContext.Result = new RedirectResult("/Login/Index");

            base.OnActionExecuting(filterContext);
        }

        /// <summary>
        /// Xoa Cache de phong tranh nut back
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
            filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
            filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
            filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            filterContext.HttpContext.Response.Cache.SetNoStore();
            base.OnResultExecuting(filterContext);
        }

        protected ActionResult IsAjaxRequest()
        {
            //Hàm được yêu cầu từ Ajax thì mới xử lý
            // Không thì sẽ bị redirect đến trang chủ
            if (!Request.IsAjaxRequest())
                return RedirectToAction("Index", "Home");
            else return null;
        }

        private bool IsPermiss(string AN)
        {
            //if (MyUser.Roles != null)
            //    return MyUser.Roles.Contains(AN);
            if (GlobalInfo.MenuUrl != null)
            {
                return GlobalInfo.MenuUrl.Contains(AN);
            }

            return false;
        }

        protected string GetCurrentUserName()
        {
            string userName = "default user";
            if (GlobalInfo.User != null)
            {
                userName = GlobalInfo.User.UserName;
            }

            return userName;
        }

        private string GetUrl(ActionDescriptor actionDescriptor)
        {
            string url = "/" + actionDescriptor.ControllerDescriptor.ControllerName + "/" + actionDescriptor.ActionName;
            return url;
        }

        protected void SetActiveMenu(string url)
        {
            ViewBag.ActiveMenus = ViewBag.ActiveMenus == null ? new System.Collections.Hashtable() : ViewBag.ActiveMenus;
            //string strInputMenuUrl = "/NguoiDung/Index";
            List<MenuModel> listMenu = globalInfo.User.ListMenu;
            if (listMenu.Count > 0)
            {
                for (int i = 0; i < listMenu.Count; i++)
                {
                    if (listMenu[i].MenuUrl.ToUpper().Equals(url.ToUpper()))
                    {
                        ViewBag.ActiveMenus[listMenu[i].ParentMenuId] = "active";
                        ViewBag.ActiveMenus[listMenu[i].MenuId] = "active";
                        ViewBag.CurrentMenuName = listMenu[i].MenuName;
                        break;
                    }
                }
            }
        }
    }
}